<template>
  <div class="monaco" ref="monacowrap"></div>
</template>
<script>
import * as monaco from "monaco-editor/esm/vs/editor/editor.main";

import bus from "@/utils/bus";
export default {
  props: {
    language: {
      type: String,
      default: "javascript"
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    code: {
      type: String,
      default: ""
    }
  },
  data() {
    return {
      editor: null
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.editor = monaco.editor.create(this.$refs.monacowrap, {
        language: this.language, // "javascript",
        theme: "vs-dark",
        automaticLayout: true,
        autoIndent: true,
        readOnly: this.readOnly,
        value: this.code || ""
      });

      // console.log("monaco.KeyMod", monaco.KeyCode);

      this.editor.addCommand(
        monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S,
        () => {
          this.$emit("save", this.editor.getValue());
        }
      );

      this.editor.addCommand(monaco.KeyCode.F5, () => {
        this.$emit("runf5", false);
      });

      this.editor.addCommand(monaco.KeyCode.F11, () => {
        this.$emit("runf11", false);
      });

      this.editor.onDidChangeModelContent(changeModel =>
        this.$emit("change", changeModel.changes)
      );
      this.$emit("editorDidMount", this.editor);
    });

    bus.$on("sidebarChange", () => {
      setTimeout(() => {
        this.editor.layout();
      }, 200);
    });
  },
  methods: {
    wrapResize() {
      const observable = new MutationObserver(() => {
        console.log("call back");
      });
      observable.observe(this.$refs.monacowrap, {
        attributes: true
        // attributeFilter: ["style"]
      });
    }
  },
  destroyed() {
    this.editor.dispose();
  }
};
</script>
<style lang="less">
.monaco {
  // width: 100%;
  height: 100%;
}

// #monaco .monaco-editor,
// #monaco .monaco-editor .overflow-guard,
// #monaco .monaco-editor .editor-scrollable {
//   height: 100% !important;
// }
</style>
